use std::sync::Mutex;

use etcd_client::{Client, ConnectOptions};
use once_cell::sync::Lazy;

static TEMP: Lazy<Mutex<Option<Client>>> = Lazy::new(Mutex::default);
static ETCD_CLIENT: Lazy<Client> = Lazy::new(|| TEMP.lock().unwrap().take().unwrap());

pub async fn connect<E: AsRef<str>, S: AsRef<[E]>>(
    endpoints: S,
    options: Option<ConnectOptions>,
) -> crate::Result<()> {
    let client = Client::connect(endpoints, options).await?;
    set_client(client);
    Ok(())
}

fn set_client(client: Client) {
    *TEMP.lock().unwrap() = Some(client);
}

pub fn get_client() -> Client {
    ETCD_CLIENT.clone()
}
